<?php

namespace backend\controllers;

use Yii;
use common\models\Base;
use common\models\Department;
use common\models\DepartmentSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\ActiveDataProvider;
use yii\helpers\Json;
use backend\components\MyTrait;

/**
 * DepartmentController implements the CRUD actions for Department model.
 */
class DepartmentController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@']
                    ]
                ]
            ],
        ];
    }


    /**
     * Lists all Department models.
     * @return mixed
     */
    public function actionIndex()
    {
        if(!Yii::$app->user->can('organization/index')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));

        //$department = Department::find()->asArray()->all();
        //$dataList = Base::getTree(0, $department);
        //return $this->render('index', [
        //    'dataList' => $dataList,
        //]);


        $searchModel = new DepartmentSearch();
        $dataProvider = Department::getTree(0, Department::getAll());

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

    }

    public function actionTree(){
        //$dataProvider = Department::get(0, Department::find()->asArray()->all());
        //echo json_encode($dataProvider);
        $array = array('id'=>1,'name'=>'aaaa');
        echo Json::encode($array);

    }

    /**
     * Displays a single Department model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($uuid)
    {
        //if(!Yii::$app->user->can('viewYourAuth')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
        //$id = Department::find()->where(['uuid'=>$id])->one()->id;
        $id = MyTrait::getId('Department',$uuid);
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Department model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        //if(!Yii::$app->user->can('createYourAuth')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));

        $model = new Department();
        $model->loadDefaultValues();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            $post = Yii::$app->request->post();
            $parent_id = isset($post['Department']['parent_id']) ? $post['Department']['parent_id'] : 0;

            if($parent_id!=0){
                $parent = $model::find()->select(['id','parent_id','name','level'])->where(['id'=>$parent_id])->one();
                $level = $parent->level;
                $model->level = $level+1;
            }
            else{
                $model->level = 1;
                $model->parent_id = 0;
            }
            $model->save();
            return $this->redirect(['index']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Department model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($uuid)
    {
        //if(!Yii::$app->user->can('updateYourAuth')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
        $id = MyTrait::getId('Department',$uuid);
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            $post = Yii::$app->request->post();
            $parent_id = isset($post['Department']['parent_id']) ? $post['Department']['parent_id'] : 0;

            if($parent_id!=0){
                $parent = $model::find()->select(['id','parent_id','name','level'])->where(['id'=>$parent_id])->one();
                $level = $parent->level;
                $model->level = $level+1;
            }
            else{
                $model->level = 1;
                $model->parent_id = 0;
            }
            $model->save();
            return $this->redirect(['index']);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Department model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($uuid)
    {
        //if(!Yii::$app->user->can('deleteYourAuth')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
        $id = MyTrait::getId('Department',$uuid);
        $this->findModel($id)->delete();
        /*$model = $this->findModel($id);
        $model->status = Status::STATUS_DELETED;
        $model->save();*/

        return $this->redirect(['index']);
    }

    /**
     * Finds the Department model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Department the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Department::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
